package com.sdonkey.score.controller;

import com.alibaba.fastjson.JSONObject;
import com.sdonkey.score.bean.AddAdPlaceLimit;
import com.sdonkey.score.bean.LoginReturnBean;
import com.sdonkey.score.model.AdPlaceLimitBean;
import com.sdonkey.score.model.AdPlacementLimitListBean;
import com.sdonkey.score.model.FinishPlacementAdBean;
import com.sdonkey.score.service.AdPlaceLimitService;
import com.sdonkey.score.service.IAccountCentralService;
import com.sdonkey.score.service.IAdPlacementService;
import com.sdonkey.score.util.StaticVariableUtil;
import com.sdonkey.score.util.SymmetricEncoder;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class AdLimitAction extends BaseController {
    @Autowired
    AdPlaceLimitService adPlaceLimitService;
    @Resource
    private IAdPlacementService adPlacementService;
    @Resource
    private IAccountCentralService accountCentralService;

    /**
     * 广告投放限制列表
     *
     * @param req
     * @param res
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("/adPlaceLimitList")
    @ResponseBody
    public Map<String, Object> onTheManagement(HttpServletRequest req, HttpServletResponse res, HttpSession session) throws Exception {
        LoginReturnBean adversiter = getCurrentUser(req);
        logger.info("----------------查询广告投放限制列表---------------");
        String advId = adversiter.getAdvId();
        Map<String, Object> model = new HashMap<String, Object>();
        List<AdPlacementLimitListBean> list = adPlaceLimitService.getAdPlaceLimitList(advId);
        long start2 = System.currentTimeMillis();
        //现在时间
        Date nowTime = new Date();
        //修改
        for (AdPlacementLimitListBean finishPlacementAdBean : list) {
            String advertiserBalance = finishPlacementAdBean.getAdvertiserBalance();
            if (advertiserBalance == null) {
                finishPlacementAdBean.setAdvertiserBalance("0.0");
                advertiserBalance = "0.0";
            }
            String adId = finishPlacementAdBean.getAdId();
            //给广告的id加密
            String aesEncode = SymmetricEncoder.AESEncode(advId, adId);
            finishPlacementAdBean.setAdId(aesEncode);
            //截止时间
            String endDateTime = finishPlacementAdBean.getEndTime();
            DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
            Date endTime = fmt.parse(endDateTime);
            //当前广告余额
            double balance = Double.parseDouble(advertiserBalance);
            //单价
            String channelPrice = finishPlacementAdBean.getChannelPrice();
            if (channelPrice == null) {
                finishPlacementAdBean.setChannelPrice("0.0");
                channelPrice = "0.0";
            }
            double price = Double.parseDouble(channelPrice);
            //被投诉状态为0
            if ("0".equals(finishPlacementAdBean.getPutStatus())) {
                finishPlacementAdBean.setStatus("0");
            }
            //者钱不够状态为5
            else if (balance - price < 0) {
                finishPlacementAdBean.setStatus("5");
            } else if (balance == 0.0) {
                finishPlacementAdBean.setStatus("5");
            }
            //时间过期修改为暂停4
            else if ((endTime.getTime() + 24 * 60 * 60 * 1000) < nowTime.getTime()) {
                finishPlacementAdBean.setStatus("4");
            }
            //下架的为不可投放
            else if ("0".equals(finishPlacementAdBean.getAdStatus())) {
                finishPlacementAdBean.setStatus("2");
            }
            //其余状态为1
            else if (!"2".equals(finishPlacementAdBean.getStatus())) {
                finishPlacementAdBean.setStatus("1");

            }
        }

        for (int i = 0; i < list.size(); i++) {
//            String adType = list.get(i).getAdType();
//            String preUrl = "video".equals(adType) ? StaticVariableUtil.SHOW_VIDEO_PRE : StaticVariableUtil.SHOW_IMG_PRE;
            //载体
            if (list.get(i).getPadVersionUrl() != null) {
//                list.get(i).setPadVersionUrl(preUrl+list.get(i).getPadVersionUrl());
                list.get(i).setTerminalType("pad");
            }
            if (list.get(i).getPcVersionUrl() != null) {
//                list.get(i).setPcVersionUrl(preUrl+list.get(i).getPcVersionUrl());
                list.get(i).setTerminalType("pc");
            }
            if (list.get(i).getMobileVersionUrl() != null) {
//                list.get(i).setMobileVersionUrl(preUrl+list.get(i).getMobileVersionUrl());
                list.get(i).setTerminalType("mobile");
            }
            if (list.get(i).getTvVersionUrl() != null) {
//                list.get(i).setTvVersionUrl(preUrl+list.get(i).getTvVersionUrl());
                list.get(i).setTerminalType("tv");
            }
            boolean flg = true;
            //不可投放
            if ("0".equals(list.get(i).getAdStatus())) {
                list.get(i).setAdStatus("不可投放");
                list.get(i).setStatus("手动下架");
                flg = false;
            } else {
                list.get(i).setAdStatus("可投放");
            }
            //广告下所有渠道的总余额
            Double advertiserBalance = 0.0;
            for (int j = 0; j < list.size(); j++) {
                //同一个广告下的渠道
                if (list.get(i).getAdId().equals(list.get(j).getAdId())) {
                    advertiserBalance += Double.valueOf(list.get(j).getAdvertiserBalance());
                    if (flg) {
                        if ("0".equals(list.get(i).getStatus()) || "0".equals(list.get(j).getStatus())) {
                            list.get(i).setStatus("0");
                            list.get(j).setStatus("0");
                        } else {

                        }

                        if ("4".equals(list.get(i).getStatus()) || "4".equals(list.get(j).getStatus())) {
                            list.get(i).setStatus("4");
                            list.get(j).setStatus("4");
                        } else {
                        }

                        if ("2".equals(list.get(i).getStatus()) || "2".equals(list.get(j).getStatus())) {
                            list.get(i).setStatus("2");
                            list.get(j).setStatus("2");
                        } else {

                        }

                        if ("1".equals(list.get(i).getStatus()) || "1".equals(list.get(j).getStatus())) {
                            list.get(i).setStatus("1");
                            list.get(j).setStatus("1");
                        } else {

                        }
                    }
                }
            }
            list.get(i).setAdvertiserBalance(advertiserBalance.toString());
        }

        for (AdPlacementLimitListBean finishPlacementAdBean : list) {
            if ("0".equals(finishPlacementAdBean.getStatus())) {
                finishPlacementAdBean.setStatus("系统下架");
            }
            if ("1".equals(finishPlacementAdBean.getStatus())) {
                finishPlacementAdBean.setStatus("投放中");
            }
            if ("2".equals(finishPlacementAdBean.getStatus())) {
                finishPlacementAdBean.setStatus("手动下架");
            }
            if ("4".equals(finishPlacementAdBean.getStatus())) {
                finishPlacementAdBean.setStatus("系统下架(时间)");
            }
            if ("5".equals(finishPlacementAdBean.getStatus())) {
                finishPlacementAdBean.setStatus("系统下架(余额)");
            }
            if("1".equals(finishPlacementAdBean.getLimitStatus())){
                finishPlacementAdBean.setLimitStatus("已开启");
            }
            if("2".equals(finishPlacementAdBean.getLimitStatus())){
                finishPlacementAdBean.setLimitStatus("已暂停");
            }
        }

        //删除掉重复的数据
        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < list.size(); j++) {
                if (list.get(i).getAdId().equals(list.get(j).getAdId()) && !list.get(i).getId().equals(list.get(j).getId())) {
                    list.remove(j);
                }
            }
        }
        model.put("beans", list);
        model.put("showVideoPre", StaticVariableUtil.SHOW_VIDEO_PRE);
        model.put("showImgPre", StaticVariableUtil.SHOW_IMG_PRE);
        return model;

    }

    //添加或修改广告限制
    @RequestMapping(value = "/setAdPlaceLimit", method = RequestMethod.POST)
    @ResponseBody
    public String addAdLimit(HttpServletRequest req, HttpServletResponse res, AddAdPlaceLimit addAdPlaceLimit) throws Exception {
        LoginReturnBean adversiter = getCurrentUser(req);
        logger.info("----------------添加或修改广告限制---------------");
        logger.info("请求的参数为：{}", addAdPlaceLimit.toString());
        int advId = Integer.parseInt(adversiter.getAdvId());
        // TODO: 2018/12/15 0015 权限验证 判断广告id是否属于广告主

        if (addAdPlaceLimit == null) {
            return createError("NOT_RIGHT", "请求参数有误").toJSONString();
        }

        if (addAdPlaceLimit.getId() == 0) {
            addAdPlaceLimit.setUserId(advId);
        }
        String adId = addAdPlaceLimit.getAdId();
        if(StringUtils.isNotBlank(adId)) {
            String aesDncode = SymmetricEncoder.AESDncode(adversiter.getAdvId(), adId);
            int trueAdId = Integer.parseInt(aesDncode);
            addAdPlaceLimit.setTrueAdId(trueAdId);
        }
        int id = adPlaceLimitService.setPlaceLimit(addAdPlaceLimit);
        if (addAdPlaceLimit.getId() != 0) {
            JSONObject result = new JSONObject();
            result.put("id", id);
            return success(result).toJSONString();
        }

        return success(new JSONObject()).toJSONString();


    }


    //添加或修改广告限制
    @RequestMapping(value = "/setAdPlaceLimit", method = RequestMethod.DELETE)
    @ResponseBody
    public String deleteAdPlaceLimit(HttpServletRequest req, HttpServletResponse res, int id) throws Exception {
        LoginReturnBean adversiter = getCurrentUser(req);
        logger.info("----------------删除广告限制---------------");
        logger.info("请求的参数为：{}", id);
        if(id == 0){
            return createError("NOT_RIGHT", "请求参数有误").toJSONString();
        }
        adPlaceLimitService.deleteAdPlaceLimit(id);


        return success(new JSONObject()).toJSONString();


    }

    @RequestMapping(value = "/getAdLimitByAdId", method = RequestMethod.POST)
    @ResponseBody
    public String queryAdLimitById(HttpServletRequest req, HttpServletResponse res, String adId) throws Exception {
        LoginReturnBean adversiter = getCurrentUser(req);
        logger.info("----------------查询广告投放限制信息---------------");
        logger.info("广告id: {}", adId);
        //解密adId

        String advId = adversiter.getAdvId();
        if (StringUtils.isBlank(adId)) {
            return createError("EOORE_PARAM", "请求参数错误").toJSONString();
        }
        String aesDncode = SymmetricEncoder.AESDncode(advId, adId);
        int trueAdId = Integer.parseInt(aesDncode);
        AdPlaceLimitBean adPlaceLimitBean = adPlaceLimitService.getAdPlacnLimitById(trueAdId);

        if (adPlaceLimitBean == null) {
            JSONObject result = new JSONObject();
            return result.toJSONString();
        }
        logger.info("----------------查询广告投放限制信息返回---------------");
        return success(JSONObject.parseObject(JSONObject.toJSON(adPlaceLimitBean).toString())).toJSONString();
    }

    @RequestMapping("/adPlaceUnLimitList")
    @ResponseBody
    public Map<String, Object> queryUnLimitAd(HttpServletRequest req, HttpServletResponse res, HttpSession session){
        LoginReturnBean adversiter = getCurrentUser(req);
        logger.info("----------------查询广告投放未限制列表---------------");
        String advId = adversiter.getAdvId();
        Map<String, Object> model = new HashMap<String, Object>();
        List<FinishPlacementAdBean> list = adPlaceLimitService.getUnLimitAdList(advId);
        long start2 = System.currentTimeMillis();
        //现在时间
        Date nowTime = new Date();
        //修改
        for (FinishPlacementAdBean finishPlacementAdBean : list) {
            String advertiserBalance = finishPlacementAdBean.getAdvertiserBalance();
            if (advertiserBalance == null) {
                finishPlacementAdBean.setAdvertiserBalance("0.0");
                advertiserBalance = "0.0";
            }
            String adId = finishPlacementAdBean.getAdId();
            //给广告的id加密
            String aesEncode = SymmetricEncoder.AESEncode(advId, adId);
            finishPlacementAdBean.setAdId(aesEncode);
            //截止时间
            String endDateTime = finishPlacementAdBean.getEndTime();
            DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
            Date endTime = null;
            try {
                endTime = fmt.parse(endDateTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //当前广告余额
            double balance = Double.parseDouble(advertiserBalance);
            //单价
            String channelPrice = finishPlacementAdBean.getChannelPrice();
            if (channelPrice == null) {
                finishPlacementAdBean.setChannelPrice("0.0");
                channelPrice = "0.0";
            }
            double price = Double.parseDouble(channelPrice);
            //被投诉状态为0
            if ("0".equals(finishPlacementAdBean.getPutStatus())) {
                finishPlacementAdBean.setStatus("0");
            }
            //者钱不够状态为5
            else if (balance - price < 0) {
                finishPlacementAdBean.setStatus("5");
            } else if (balance == 0.0) {
                finishPlacementAdBean.setStatus("5");
            }
            //时间过期修改为暂停4
            else if ((endTime.getTime() + 24 * 60 * 60 * 1000) < nowTime.getTime()) {
                finishPlacementAdBean.setStatus("4");
            }
            //下架的为不可投放
            else if ("0".equals(finishPlacementAdBean.getAdStatus())) {
                finishPlacementAdBean.setStatus("2");
            }
            //其余状态为1
            else if (!"2".equals(finishPlacementAdBean.getStatus())) {
                finishPlacementAdBean.setStatus("1");

            }
        }

        for (int i = 0; i < list.size(); i++) {
//            String adType = list.get(i).getAdType();
//            String preUrl = "video".equals(adType) ? StaticVariableUtil.SHOW_VIDEO_PRE : StaticVariableUtil.SHOW_IMG_PRE;
            //载体
            if (list.get(i).getPadVersionUrl() != null) {
//                list.get(i).setPadVersionUrl(preUrl+list.get(i).getPadVersionUrl());
                list.get(i).setTerminalType("pad");
            }
            if (list.get(i).getPcVersionUrl() != null) {
//                list.get(i).setPcVersionUrl(preUrl+list.get(i).getPcVersionUrl());
                list.get(i).setTerminalType("pc");
            }
            if (list.get(i).getMobileVersionUrl() != null) {
//                list.get(i).setMobileVersionUrl(preUrl+list.get(i).getMobileVersionUrl());
                list.get(i).setTerminalType("mobile");
            }
            if (list.get(i).getTvVersionUrl() != null) {
//                list.get(i).setTvVersionUrl(preUrl+list.get(i).getTvVersionUrl());
                list.get(i).setTerminalType("tv");
            }
            boolean flg = true;
            //不可投放
            if ("0".equals(list.get(i).getAdStatus())) {
                list.get(i).setAdStatus("不可投放");
                list.get(i).setStatus("手动下架");
                flg = false;
            } else {
                list.get(i).setAdStatus("可投放");
            }
            //广告下所有渠道的总余额
            Double advertiserBalance = 0.0;
            for (int j = 0; j < list.size(); j++) {
                //同一个广告下的渠道
                if (list.get(i).getAdId().equals(list.get(j).getAdId())) {
                    advertiserBalance += Double.valueOf(list.get(j).getAdvertiserBalance());
                    if (flg) {
                        if ("0".equals(list.get(i).getStatus()) || "0".equals(list.get(j).getStatus())) {
                            list.get(i).setStatus("0");
                            list.get(j).setStatus("0");
                        } else {

                        }

                        if ("4".equals(list.get(i).getStatus()) || "4".equals(list.get(j).getStatus())) {
                            list.get(i).setStatus("4");
                            list.get(j).setStatus("4");
                        } else {
                        }

                        if ("2".equals(list.get(i).getStatus()) || "2".equals(list.get(j).getStatus())) {
                            list.get(i).setStatus("2");
                            list.get(j).setStatus("2");
                        } else {

                        }

                        if ("1".equals(list.get(i).getStatus()) || "1".equals(list.get(j).getStatus())) {
                            list.get(i).setStatus("1");
                            list.get(j).setStatus("1");
                        } else {

                        }
                    }
                }
            }
            list.get(i).setAdvertiserBalance(advertiserBalance.toString());
        }

        for (FinishPlacementAdBean finishPlacementAdBean : list) {
            if ("0".equals(finishPlacementAdBean.getStatus())) {
                finishPlacementAdBean.setStatus("系统下架");
            }
            if ("1".equals(finishPlacementAdBean.getStatus())) {
                finishPlacementAdBean.setStatus("投放中");
            }
            if ("2".equals(finishPlacementAdBean.getStatus())) {
                finishPlacementAdBean.setStatus("手动下架");
            }
            if ("4".equals(finishPlacementAdBean.getStatus())) {
                finishPlacementAdBean.setStatus("系统下架(时间)");
            }
            if ("5".equals(finishPlacementAdBean.getStatus())) {
                finishPlacementAdBean.setStatus("系统下架(余额)");
            }
        }

        //删除掉重复的数据
        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < list.size(); j++) {
                if (list.get(i).getAdId().equals(list.get(j).getAdId()) && !list.get(i).getId().equals(list.get(j).getId())) {
                    list.remove(j);
                }
            }
        }
        model.put("beans", list);
        model.put("showVideoPre", StaticVariableUtil.SHOW_VIDEO_PRE);
        model.put("showImgPre", StaticVariableUtil.SHOW_IMG_PRE);
        return model;

    }
}
